package controllers

import (
	"bytes"
	"fmt"
	"k8s.io/apimachinery/pkg/util/yaml"

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	networkv1 "k8s.io/api/networking/v1"
	myAppsv1 "mashibing.com/pkg/mashibing-deployment/api/v1"
	"text/template"
)

func parseTemplate(templateName string, md *myAppsv1.MsbDeployment) []byte {
	//tmpl, err := template.ParseFiles(fmt.Sprintf("controllers/templates/%s", templateName))
	tmpl, err := template.ParseFiles(fmt.Sprintf("templates/%s", templateName))
	if err != nil {
		return []byte{}
	}
	b := new(bytes.Buffer)
	err = tmpl.Execute(b, md)
	if err != nil {
		return []byte{}
	}

	return b.Bytes()
}

func NewDeployment(md *myAppsv1.MsbDeployment) (*appsv1.Deployment, error) {
	deployment := new(appsv1.Deployment)
	if err := yaml.Unmarshal(parseTemplate("deployment.yaml", md), deployment); err != nil {
		return deployment, err
	}

	return deployment, nil
}

func NewService(md *myAppsv1.MsbDeployment) (*corev1.Service, error) {
	svc := new(corev1.Service)
	if err := yaml.Unmarshal(parseTemplate("service-ingress.yaml", md), svc); err != nil {
		return svc, err
	}

	return svc, nil
}

func NewNodePortService(md *myAppsv1.MsbDeployment) (*corev1.Service, error) {
	svc := new(corev1.Service)
	if err := yaml.Unmarshal(parseTemplate("service-nodeport.yaml", md), svc); err != nil {
		return svc, err
	}

	return svc, nil
}

func NewIngress(md *myAppsv1.MsbDeployment) (*networkv1.Ingress, error) {
	ng := new(networkv1.Ingress)
	if err := yaml.Unmarshal(parseTemplate("ingress.yaml", md), ng); err != nil {
		return ng, err
	}

	return ng, nil
}
